from datetime import datetime
from app import db

class User(db.Model):
    """用户模型"""
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    openid = db.Column(db.String(64), unique=True, index=True, nullable=False, comment='微信openid')
    nickname = db.Column(db.String(64), comment='微信昵称')
    avatar_url = db.Column(db.String(255), comment='头像URL')
    phone = db.Column(db.String(20), unique=True, index=True, comment='手机号')
    gender = db.Column(db.SmallInteger, default=0, comment='性别: 0未知 1男 2女')
    is_active = db.Column(db.Boolean, default=True, comment='是否活跃')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    orders = db.relationship('Order', back_populates='user', lazy='dynamic')
    
    def __repr__(self):
        return f'<User {self.id}: {self.nickname or "未命名"}>'
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        return {
            'id': self.id,
            'nickname': self.nickname,
            'avatar_url': self.avatar_url,
            'phone': self.phone,
            'gender': self.gender,
            'is_active': self.is_active,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }